<template>
	<view class="content">
		<uni-list :border="true"  v-if="visitorList.length!=0">
		    <uni-list-chat :key="item.visitor_id" :avatar-circle="true" clickable @click="chatVisitor($event,item.visitor_id)" :title="item.username" v-for="item in visitorList" :avatar="item.avator" :note="showLastMessage(item.last_message)" :time="formatTime(item.last_time)" badge-positon="left" :badge-text="showUnreadNum(item.unread_num)"></uni-list-chat>
		</uni-list>
		<view class="flyNotice" v-if="visitorList.length==0">
			<view><image style="width: 135px;height: 132px;" src="@/static/images/no-chat.png"></image></view>
			<view style="color: #333;">暂无在线访客</view>
			<view>没有要处理的对话，休息一下吧</view>
		</view>
	</view>

</template>

<script>
	import visitorHelper from '../../common/visitors.js';
	import toolsHelper from '../../common/tools.js';
	import WebSocketClass from '../../common/socket.js'
	const app = getApp();
	export default {
		data() {
			return {
				title: 'Hello',
				baseUrl: getApp().globalData.baseUrl,
				wsBaseUrl: getApp().globalData.wsBaseUrl,
				visitorList: [],
				token: "",
				timer: null,
				wsOpen: false,
				noticeContent:"通知: 无",
				innerAudioContext:null,
			}
		},
		// 页面显示
		onShow() {
			let _this = this;
			let res = uni.getStorageSync('app');
			console.log(res);
			if (res) {
				this.token = res.token;
			}
			let domainInfo = uni.getStorageSync('domain');
			if (domainInfo) {
				this.baseUrl = domainInfo.domain;
				this.wsBaseUrl=toolsHelper.getWsUrl(domainInfo.domain);
			}
			this.checkAuth();
			this.initPush();
		},
		onLoad() {

		},
		methods: {
			//初始化socket
			initSocket(){
			
				      // 如果已经有sockt实例
				      if (app.globalData.socketObj) {
				        // 如果sockt实例未连接
				        if (!app.globalData.socketObj.isConnect) {
				          app.globalData.socketObj.initSocket()
				        }
				      } else {
				        app.globalData.socketObj = new WebSocketClass(
				          this.wsBaseUrl + "?token=" + this.token,
				          60
				        )
				        app.globalData.socketObj.initSocket()
				      }
			},
			//用户实时上下线
			onlineIntime() {
				var _this = this;
				var timer = null;
				// uni.connectSocket({
				// 	url: this.wsBaseUrl + "?token=" + this.token,
				// });
				// uni.onSocketClose((res) => {
				// 	clearInterval(timer);
				// 	console.log("WebSocket 连接断开");
				// });
				// uni.onSocketOpen((res) => {
				// 	console.log("WebSocket 连接已打开");;
				// 	let _this = this;
				// 	let mes = {}
				// 	mes.type = "ping";
				// 	mes.data = "";
				// 	timer = setInterval(function() {
				// 		uni.sendSocketMessage({
				// 			data: JSON.stringify(mes),
				// 		});
				// 	}, 5000)

				// });
				uni.onSocketMessage((res) => {
				//uni.$on('message',(res) => {
					var redata = JSON.parse(res.data);
					switch (redata.type) {
						case "allUsers":
							break;
						case "userOnline":
							_this.addOnlineUser(redata.data);
							toolsHelper.playVoice();
							break;
						case "userOffline":
						console.log("下线");
							_this.removeOfflineUser(redata.data);
							break;
						case "notice":
							break;
						case "message":
							_this.recvMessage(redata.data);
							break;
					}
				});
			},
			getOnlineUser() {
				let _this = this;
				var baseUrl = this.baseUrl;
				uni.request({
					url: baseUrl + '/kefu/onlineVisitors?token=' + _this.token,
					method: 'GET',
					success: function(res) {
						console.log(res);
						if (!res.data.result) {
							return;
						}
						var list=res.data.result;
						for(var i=0;i<list.length;i++){
							list[i].avator=toolsHelper.getImageUrl(list[i].avator,_this.baseUrl);
						}
						_this.visitorList = list;
					},
					fail: function(res) {}
				});
			},
			addOnlineUser(retData) {
				var list=this.visitorList;
				retData.avator=toolsHelper.getImageUrl(retData.avator,this.baseUrl);
				this.visitorList = visitorHelper.addVisitor(list,retData);
			},
			//处理当前在线用户列表
			removeOfflineUser: function(retData) {
				var list=this.visitorList;
				list= visitorHelper.removeVisitor(list,retData.visitor_id);
				this.visitorList=list;
			},
			//点击
			chatVisitor(e, visitorId) {
				uni.navigateTo({
					url: '/pages/index/detail?visitor_id=' + visitorId
				})
			},
			recvMessage(msg) {
				this.visitorList = visitorHelper.receiveMessage(this.visitorList,msg);
				this.showNoticeBar(msg.name+":"+ msg.content);
				if(msg.is_kefu != "yes"){
					toolsHelper.playVoice();
				}
			},
			initPush(){
				var _this=this;
			},
			showNotice(msg){
				// if (uni.getSystemInfoSync().platform == "android") {
				// 	if(window.plus){
				// 		var options = {cover:false};
				// 		plus.push.createMessage(msg,"LocalMSG",options);
				// 	}
				// 	if(uni.vibrate){
				// 		uni.vibrate({
				// 		    success: function () {
				// 		        console.log('success');
				// 		    }
				// 		});
				// 	}
				// }
			},
			showNoticeBar(msg){
				var _this=this;
				_this.noticeContent=msg;
			},
			checkAuth() {
				var _this = this;
				uni.request({
					url: _this.baseUrl + '/uc/v1/refreshToken?token=' + _this.token,
					method: 'POST',
					header: {
						'Content-Type': 'application/x-www-form-urlencoded'
					},
					success: function(res) {
						var code = res.data.code;
						if (code != 20000) {
							uni.navigateTo({
								url: '/pages/index/login'
							});
						} else {
							uni.setStorageSync("app", {
								token: res.data.result.token,
							});
							_this.token=res.data.result.token;
							_this.initSocket();
							_this.onlineIntime();
							_this.getOnlineUser();
						}
					}
				});
			},
			registerClient(clientId) {
				let _this = this;
				var baseUrl = this.baseUrl;
				uni.request({
					url: baseUrl + '/kefu/appClient?token='+_this.token,
					data:{client_id:clientId},
					method: 'POST',
					header: {
						'Content-Type': 'application/x-www-form-urlencoded'
					},
					success: function(res) {
						console.log(res);
					}
				});
			},
			showLastMessage(mes){
				if(mes==""){
					return "无消息";
				}
				mes=toolsHelper.replaceHtml(mes);
				return mes
			},
			showUnreadNum(num){
				if(num==0||num=="0"){
					return "dot";
				}
				return num;
			},
			//格式化时间
			formatTime(time) {
				var time = Math.round(new Date(time).getTime()/1000);
				return toolsHelper.beautifyTime(time);
			},
		}
	}
</script>

<style>
	page {
	   background-color: #eef0f6;
	}

</style>
